package com.kefu.chat.service;

import java.util.ArrayList;
import java.util.List;

import com.kefu.chat.mapper.ChatSessionMsgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.chat.model.ChatData;
import com.kefu.chat.model.ChatSession;
import com.kefu.chat.model.ChatSessionMsg;
import com.kefu.chat.model.ChatUser;
import com.kefu.chat.util.ChatConstant;
import com.kefu.common.service.AbstractKefuService;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;

import javax.annotation.Resource;

@Service
public class ChatSessionMsgService  extends AbstractKefuService<ChatSessionMsg>  {
    @Autowired
    private ChatCacheService chatCacheService;
    @Autowired
    private ChatSessionService chatSessionService;
    @Resource
    private ChatSessionMsgMapper chatSessionMsgMapper;

     
    public List<ChatSessionMsg> getSessionMsg(String sessionId) {
        if (StrUtil.isBlank(sessionId)) {
            return new ArrayList<>();
        }
        return list(Wrappers.lambdaQuery(ChatSessionMsg.class).eq(ChatSessionMsg::getSessionId,sessionId)
                .orderByAsc(ChatSessionMsg::getMsgTime).last("limit 500"));
    }

     
    public void insertSessionMsg(ChatSessionMsg msg) {
        logger.info("insertSessionMsg_start:{}",msg);
        String sessionId = msg.getSessionId();
        long time = System.currentTimeMillis();
        ChatData chatData = chatCacheService.getData(sessionId);
        Integer sensitiveAdmin = null;
        Integer sensitiveUser = null;
        if (chatData == null) {
            chatData = new ChatData();
            chatData.setSessionId(sessionId);
            chatData.setUserId(msg.getUserId());
            chatData.setAdminId(msg.getAdminId());
            ChatUser chatUser = chatCacheService.getUser(msg.getUserId());
            if(chatUser!=null) chatData.setChannelId(chatUser.getChannelId());
        }
        chatData.setSender(msg.getSender());
        chatData.setSenderType(msg.getSenderType());
        chatData.setSenderName(msg.getSenderName());
        chatData.setLastMsgType(msg.getMsgType());
        if (msg.getMsgType() == 1) {
            chatData.setLastMsgContent(msg.getMsgContent());
        }
        if (msg.getSenderType() == ChatConstant.msg_sender_user) {
            chatData.setUserMsgTime(time);
            chatData.setUserMsgContent(msg.getMsgContent());
            chatData.setUserMsgCount(chatData.getUserMsgCount() + 1);
            if (msg.getReceiveType() == ChatConstant.msg_sender_admin) {
                chatData.setUserWaitReply(1);
                chatData.setUserAdminMsgCount(chatData.getUserAdminMsgCount() + 1);
            }
            if (msg.getSensitiveFlag() != null && msg.getSensitiveFlag() == 1) {
                sensitiveUser = 1;
            }
        } else if (msg.getSenderType() == ChatConstant.msg_sender_admin) {
            chatData.setAdminMsgTime(time);
            chatData.setAdminTimeout(0);
            chatData.setAdminMsgCount(chatData.getAdminMsgCount() + 1);
            if (chatData.getUserWaitReply() == 1) {
                chatData.getReplyDuration().add((time - chatData.getUserMsgTime()) / 1000);
                chatData.setUserWaitReply(0);
            }
            if (msg.getSensitiveFlag() != null && msg.getSensitiveFlag() == 1) {
                sensitiveAdmin = 1;
            }
        } else if (msg.getSenderType() == ChatConstant.msg_sender_robot) {
            chatData.setRobotAnswerType(msg.getAnswerType());
            chatData.setRobotMsgCount(chatData.getRobotMsgCount() + 1);
            if (StrUtil.isNotBlank(msg.getRobotSuggest())) {
                chatData.setRobotSuggest(msg.getRobotSuggest());
            } else {
                chatData.setRobotSuggest("");
            }
        }
        chatData.setLastMsgTime(time);
        chatCacheService.setData(chatData); //更新会话缓存
        //插入聊天记录
        ThreadUtil.execute(() -> {
            super.save(msg);
            logger.info("insertSessionMsg_end:{}",msg);
        });
        if (sensitiveAdmin != null || sensitiveUser != null) {
            ChatSession chatSession = new ChatSession();
            chatSession.setSessionId(msg.getSessionId());
            chatSession.setSensitiveAdmin(sensitiveAdmin);
            chatSession.setSensitiveUser(sensitiveUser);
            //更新会话纪录，敏感词状态
            ThreadUtil.execute(() -> chatSessionService.update(chatSession));
        }
    }

    public List<ChatSessionMsg> getHistorySessionMsg(String userId, long maxTime, int pageSize) {
        if (StrUtil.isBlank(userId)) {
            return null;
        }
        LambdaQueryWrapper<ChatSessionMsg> wrapper = Wrappers.lambdaQuery(ChatSessionMsg.class);
        wrapper.eq(ChatSessionMsg::getUserId, userId);
        wrapper.lt(ChatSessionMsg::getMsgTime, maxTime > 0 ? maxTime : System.currentTimeMillis());
        wrapper.orderByDesc(ChatSessionMsg::getMsgTime);
        Page<ChatSessionMsg> page=new Page<>(1, Math.min(pageSize, 20),false);
        return chatSessionMsgMapper.selectPage(page,wrapper).getRecords();
    }
}
